﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace TencentMapSdk
{
    /// <summary>
    /// Api请求基类
    /// </summary>
    public class BaseApi : IDisposable
    {
        /// <summary>
        /// 腾讯地图服务器基地址
        /// </summary>
        protected const string host = "https://apis.map.qq.com";
        static HttpClient client = new HttpClient();

        /// <summary>
        /// Get请求
        /// </summary>
        /// <typeparam name="Response"></typeparam>
        /// <param name="url"></param>
        /// <returns></returns>
        protected static Response Get<Response>(string url, out string body)
        {
            using HttpResponseMessage response = client.GetAsync(url).Result;
            body = response.Content.ReadAsStringAsync().Result;
            Response res = JsonConvert.DeserializeObject<Response>(body);
            return res;
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <typeparam name="Response"></typeparam>
        /// <param name="url"></param>
        /// <param name="post"></param>
        /// <returns></returns>
        protected static Response Post<Response>(string url, string post, out string body)
        {
            using HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, url);
            using StringContent content = new StringContent(post, Encoding.UTF8);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            requestMessage.Content = content;

            using HttpResponseMessage response = client.SendAsync(requestMessage).Result;
            body = response.Content.ReadAsStringAsync().Result;
            Response res = JsonConvert.DeserializeObject<Response>(body);
            return res;

        }

        /// <summary>
        /// Get请求获取二进制流文件
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        protected static Stream GetFile(string url)
        {
            using HttpResponseMessage response = client.GetAsync(url).Result;
            using Stream stream=response.Content.ReadAsStreamAsync().Result;
            MemoryStream stream1 = new MemoryStream();
            stream.CopyTo(stream1);
            return stream1;
        }

        /// <summary>
        /// 释放托管资源
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        public void Dispose()
        {
            client?.Dispose();
        }
    }
}
